package com.hugoo.extra.xlsx;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author Hugoo.Chan
 */
class WB {

    private static final String wb_t = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><workbook xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"><workbookPr date1904=\"false\"/><bookViews><workbookView activeTab=\"0\"/></bookViews><sheets>",
            wb_e = "</sheets></workbook>",
            wbr_t = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"> <Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings\" Target=\"sharedStrings.xml\"/><Relationship Id=\"rId2\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\" Target=\"styles.xml\"/>",
            wbr_e = "</Relationships>",
            ct_t = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>  <Default Extension=\"xml\" ContentType=\"application/xml\"/>  <Override PartName=\"/docProps/app.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.extended-properties+xml\"/>  <Override PartName=\"/docProps/core.xml\" ContentType=\"application/vnd.openxmlformats-package.core-properties+xml\"/>  <Override PartName=\"/xl/sharedStrings.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml\"/>  <Override PartName=\"/xl/styles.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\"/>  <Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/>",
            ct_e = "</Types>";
    StringBuilder s_ct, s_wb, s_wbr;
    int i = 0, j = 2;
    private static final String[][] sl = {
        {"_rels/.rels", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">  <Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"xl/workbook.xml\"/>  <Relationship Id=\"rId2\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties\" Target=\"docProps/app.xml\"/>  <Relationship Id=\"rId3\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\" Target=\"docProps/core.xml\"/></Relationships>"},
        {"docProps/app.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\"><Application>Apache POI</Application></Properties>"},
        {"docProps/core.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><coreProperties xmlns=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><dcterms:created xsi:type=\"dcterms:W3CDTF\">2012-05-19T05:48:18Z</dcterms:created><dc:creator>Apache POI</dc:creator></coreProperties>"},
        {"xl/styles.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"><numFmts count=\"0\"/><fonts count=\"3\"><font><sz val=\"11.0\"/><color indexed=\"8\"/><name val=\"Calibri\"/><family val=\"2\"/><scheme val=\"minor\"/></font><font><name val=\"Calibri\"/><sz val=\"9.0\"/></font><font><name val=\"Calibri\"/><sz val=\"10.0\"/><b val=\"true\"/></font></fonts><fills count=\"2\"><fill><patternFill patternType=\"none\"/></fill><fill><patternFill patternType=\"darkGray\"/></fill></fills><borders count=\"5\"><border><left/><right/><top/><bottom/><diagonal/></border><border><bottom style=\"thin\"/></border><border><right style=\"thin\"/><bottom style=\"thin\"/></border><border><right style=\"thin\"/><bottom style=\"thin\"><color indexed=\"0\"/></bottom></border><border><right style=\"thin\"><color indexed=\"0\"/></right><bottom style=\"thin\"><color indexed=\"0\"/></bottom></border></borders><cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs><cellXfs count=\"6\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\"/><xf numFmtId=\"0\" fontId=\"1\" fillId=\"0\" borderId=\"4\" xfId=\"0\" applyFont=\"true\" applyBorder=\"true\"><alignment horizontal=\"left\"/></xf><xf numFmtId=\"10\" fontId=\"1\" fillId=\"0\" borderId=\"4\" xfId=\"0\" applyFont=\"true\" applyNumberFormat=\"true\" applyBorder=\"true\"><alignment horizontal=\"right\"/></xf><xf numFmtId=\"4\" fontId=\"1\" fillId=\"0\" borderId=\"4\" xfId=\"0\" applyFont=\"true\" applyNumberFormat=\"true\" applyBorder=\"true\"><alignment horizontal=\"right\"/></xf><xf numFmtId=\"0\" fontId=\"1\" fillId=\"0\" borderId=\"4\" xfId=\"0\" applyFont=\"true\" applyNumberFormat=\"true\" applyBorder=\"true\"><alignment horizontal=\"right\"/></xf><xf numFmtId=\"0\" fontId=\"2\" fillId=\"0\" borderId=\"4\" xfId=\"0\" applyFont=\"true\" applyBorder=\"true\"><alignment horizontal=\"center\"/></xf></cellXfs></styleSheet>"},
        {"xl/sharedStrings.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sst count=\"0\" uniqueCount=\"0\" xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"/>"}
    };
    private static final String[][] dsl = {
        {"xl/workbook.xml", "WB"},
        {"[Content_Types].xml", "CT"},
        {"xl/_rels/workbook.xml.rels", "WR"}
    };

    public WB() {
        s_ct = new StringBuilder(ct_t);// [Content_Types].xml
        s_wb = new StringBuilder(wb_t);// /xl/workbook.xml
        s_wbr = new StringBuilder(wbr_t);// /xl/_rels/workbook.xml.rels
    }
    Map m = new HashMap();

    public void addSheet(String name, File path) {
        i++;
        j++;
        m.put("sheet" + i, path);
        s_ct.append("<Override PartName=\"/xl/worksheets/sheet").append(i).append(".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"/>");
        s_wb.append("<sheet name=\"").append(name).append("\" r:id=\"rId").append(j).append("\" sheetId=\"").append(i).append("\"/>");
        s_wbr.append("<Relationship Id=\"rId").append(j).
                append("\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\" Target=\"worksheets/sheet").
                append(i).append(".xml\"/>");
    }

    public void pack() {
        m.put("CT", s_ct.append(ct_e).toString());
        m.put("WB", s_wb.append(wb_e).toString());
        m.put("WR", s_wbr.append(wbr_e).toString());
    }

    public void pkg(OutputStream out) throws IOException {
        ZipOutputStream zos = new ZipOutputStream(out);
        zos.setLevel(1);//设置压缩等级为1，以最快方式压缩
        for (String[] x : sl) {//包装公共部份
            zos.putNextEntry(new ZipEntry(x[0]));
            zos.write(x[1].getBytes());
        }
        for (String[] x : dsl) {//包装私有部份 dsl
            zos.putNextEntry(new ZipEntry(x[0]));
            String t = (String) m.get(x[1]);
            zos.write(t.getBytes("UTF-8"));
        }
        for (; i > 0; i--) {
            zos.putNextEntry(new ZipEntry("xl/worksheets/sheet" + i + ".xml"));
            File f = (File) m.get("sheet" + i);
            InputStream is = new FileInputStream(f);
            copyStream(is, zos);
            is.close();
            f.delete();
        }
        zos.close();
    }

    private static void copyStream(InputStream in, OutputStream out) throws IOException {
        byte[] chunk = new byte[1048576];//1M-1048576
        int count;
        while ((count = in.read(chunk)) >= 0) {
            out.write(chunk, 0, count);
        }
    }
}
